package org.example.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author WZW
 * @date 2020/7/11
 */
public class RacingCarDecoder extends ByteToMessageDecoder {

    public static final int BASE_LENGTH = 4 + 4;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < BASE_LENGTH){
            return;
        }
        if (in.readableBytes() > 2048) {
            in.skipBytes(in.readableBytes());
        }

        int beginReader;

        while (true) {
            beginReader = in.readerIndex();
            in.markReaderIndex();
            if (in.readInt() == 0x76) {
                break;
            }
            in.resetReaderIndex();
            in.readByte();

            if (in.readableBytes() < BASE_LENGTH){
                return;
            }
        }

        int length = in.readInt();
        if (in.readableBytes() < length){
            in.readerIndex(beginReader);
            return;
        }

        byte[] data = new byte[length];

        in.readBytes(data);

        RacingCarProtocol protocol = new RacingCarProtocol(data.length, data);
        out.add(protocol);
    }
}
